package com.yvan.leto.server.config;


import com.yvan.YvanUtil;
import com.yvan.leto.server.domain.Env;
import com.yvan.leto.server.domain.UserAgent;
import com.yvan.leto.server.security.JwtHelper;
import com.yvan.leto.server.service.EnvService;
import com.yvan.leto.server.service.UserService;
import lombok.val;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * freemarker 的静态资源函数
 * Created by luoyifan on 2017/3/28.
 */
@Component
public class FreemarkerFunctions {

    @Value("${yvan.static_domain}")
    private String staticDomain;

    @Value("${yvan.static_version}")
    private String staticVersion;

    @Autowired
    private UserService userService;

    @Autowired
    private EnvService envService;

    /**
     * 第三方前端库函数资源
     * 根据 jzt.static_domain 的配置，生成静态资源路径
     * <p/>
     * 比如 /css/base.css 会根据配置变成
     * http://static.yyjzt.com/js/jquery.js 或
     * /static/js/jquery.js
     */
    @FreemarkerFunction("s3")
    public String s3(String resourcePath) {
        return staticDomain + resourcePath;
    }

    /**
     * 自己编写的前端库资源
     * 根据 jzt.static_domain 的配置，生成静态资源路径
     * <p/>
     * 比如 /css/base.css 会根据配置变成
     * http://static.yyjzt.com/css/base.css?v=20170328 或
     * /static/css/base.css?v=20170328
     */
    @FreemarkerFunction("s0")
    public String s0(String resourcePath) {
        return staticDomain + resourcePath + "?v=" + staticVersion;
    }

    @FreemarkerFunction("islogined")
    public boolean isLogined() {
        return JwtHelper.isLogined();
    }

    @FreemarkerFunction("userName")
    public String userName() {
        if (isLogined()) {
            val loginName = JwtHelper.getLoginName();
            if (StringUtils.isEmpty(loginName)) {
                return "";
            }
            UserAgent userAgent = userService.getByLoginName(loginName);
            if (userAgent == null || StringUtils.isEmpty(userAgent.getRealName())) {
                return loginName;
            }
            return userAgent.getRealName();
        }
        return "";
    }

    @FreemarkerFunction("envs")
    public List<Env> envs() {
        return envService.selectAll();
    }

    @FreemarkerFunction("envs_json")
    public String envsJson() {
        return YvanUtil.toJsonPretty(envs());
    }
}
